package com.wkbb.basic.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wkbb.basic.feign.TcCloudFeignService;
import com.wkbb.basic.feign.WxFeignService;
import com.wkbb.basic.mapper.*;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.*;
import com.wkbb.basic.utils.YouTuUtil;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.config.ServiceConfig;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.im.COSCredentialDto;
import com.wkbb.common.dto.wx.AccountDto;
import com.wkbb.common.enums.CosFileTypeEnum;
import com.wkbb.common.enums.CountTypeEnum;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.UuIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lilin
 */
@Service
@Slf4j
public class UserFacePersonServiceImpl extends BaseServiceImpl<UserFacePersonConfig> implements UserFacePersonConfigService {

    @Autowired
    public UserFacePersonConfigMapper userFacePersonConfigMapper;

    @Autowired
    public OrganizationMapper organizationMapper;

    @Autowired
    public UserMapper userMapper;

    @Autowired
    private WxFeignService wxFeignService;

    @Autowired
    private YouTuService youTuService;

    @Autowired
    private TcCloudFeignService tcCloudFeignService;

    @Autowired
    private ServiceConfig serviceConfig;

    @Autowired
    private ImportLogMapper importLogMapper;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private FamilyService familyService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private YoutuPersonMapper youtuPersonMapper;

    @Autowired
    private  WebankService webankService;

    @Autowired
    public void setMapper(UserFacePersonConfigMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids, String deleteBy) throws Exception {
        if (ids.isEmpty()) {
            return;
        }

        for (Long id : ids) {
            if (id == null || id == 0) {
                return;
            }

            UserFacePersonConfig userFacePersonConfig = new UserFacePersonConfig();
            userFacePersonConfig.setId(id);
            userFacePersonConfig.setStatus(false);
            update(userFacePersonConfig);
        }
    }

    @Override
    public List<UserFacePersonConfig> getUserFacePersonConfigList(Map<String, Object> params, Short type) {
        switch (type) {
            case 0:
                return userFacePersonConfigMapper.getStuFamFacePersonConfig(params);
            case 1:
                return userFacePersonConfigMapper.getTeacherFacePersonConfig(params);
            default:
                return null;
        }
    }

    @Override
    public List<Object> saveImportData(UserDto userDto, List<Object[]> data) throws Exception {
        List<Object> errorMsgUserIdData = new ArrayList<>();
        //学校ID*
        //学校名称*
        //旧版本教职工ID*
        //教职工姓名*
        //手机号*
        //岗位*
        //性别*
        //生日
        //@通过2.0旧的oldOrgId获取newOrgId
        String faceResult = null;
        Long orgId = null;
        Boolean flag = false;
        if (null != data.get(0)[0] && !"".equals(data.get(0)[0])) {
            Organization newOrganization = null;
            //1是2.0迁移,2是智慧校园迁移.里面学校ID和用户ID有区别
            newOrganization = organizationMapper.getNewOrgByOld(Long.valueOf(data.get(0)[0].toString()));
            if (null != newOrganization) {
                orgId = newOrganization.getId();
            }
        }

        if (null != orgId) {
            //通过组织ID获取accountId
            for (Object[] objects : data) {
                User user = null;
                Long oldUserId = (Long.valueOf(objects[1].toString()));
                user = userMapper.getNewUserByOld(oldUserId);


                ResultDTO<AccountDto> result = wxFeignService.getAccountByOrg(orgId);
                if (result.isSuccess() && null != user) {
                    AccountDto accountDto = result.getData();
                    if (null != accountDto) {
                                //通过网络流的方式上传图片到cos
                                ResultDTO<COSCredentialDto> resultDTO = tcCloudFeignService.getCredential();
                                if (ResultDTO.checkSuccess(resultDTO) && resultDTO.getData() != null) {

                                    ResultDTO<Object> picUrlResult = tcCloudFeignService.getPicUrl(resultDTO.getData().getCredentials().getTmpSecretId(), resultDTO.getData().getCredentials().getTmpSecretKey(), resultDTO.getData().getCredentials().getSessionToken(), CosFileTypeEnum.FACETYPE.getValue(), CountTypeEnum.IMGTYPE.getValue(), objects[5].toString());
                                    if (ResultDTO.checkSuccess(picUrlResult) && picUrlResult.getData() != null) {
                                        youTuService.importUserFace(picUrlResult.getData().toString(), user.getUserCode(), orgId, accountDto.getId(), user.getId(),false);
                                        flag = true;
                                    }
                                }
                    }
                }
                if (null == user || !flag) {
                    errorMsgUserIdData.add(Long.valueOf(objects[1].toString()));
                }
            }
        }
        return errorMsgUserIdData;
    }

    @Override
    public List<Object> saveCamImportData(UserDto userDto, List<Object[]> data) throws Exception {
        List<Object> errorMsgUserIdData = new ArrayList<>();
        //学校ID*
        //学校名称*
        //旧版本教职工ID*
        //教职工姓名*
        //手机号*
        //岗位*
        //性别*
        //生日
        //@通过2.0旧的oldOrgId获取newOrgId
        String youTuResult = null;
        Long orgId = null;

        ImportLog importLog = new ImportLog();
        importLog.setCreateBy("超级管理员");
        importLog.setType(new Short(10+""));
        importLog.setStatus(true);
        if (null != data.get(0)[0] && !"".equals(data.get(0)[0])) {
            //1是2.0迁移,2是智慧校园迁移.里面学校ID和用户ID有区别
            Map<String, Object> params = new HashMap<>();
            params.put("smartOrgId", data.get(0)[0].toString());
            Organization newOrganization = organizationService.getByMapParams(params);

            if (null != newOrganization) {
                orgId = newOrganization.getId();
                importLog.setOrgId(orgId);
            }
        }
        //通过组织ID获取accountId
        for (Object[] objects : data) {
            Boolean flag = false;
            System.out.println(objects[1].toString());
            User user = null;
            if (null != objects[9]) {
                Map<String, Object> params = new HashMap<>(1);
                params.put("smartUserId", objects[1].toString());
                //3学生,2老师,1家长
                if(null!=objects[9]){
                    switch (Integer.parseInt(objects[9].toString())){
                        case  1:
                            Family family = familyService.getByMapParams(params);
                            if (null != family) {
                                user = userMapper.getByPrimaryKey(family.getUserId());
                            }
                            break;
                        case  2:
                            Employee employee = employeeMapper.getByMapParams(params);
                            if (null != employee) {
                                user = userMapper.getByPrimaryKey(employee.getUserId());
                            }
                            break;
                        default:
                            StudentInfoDto studentInfoByMapParams = studentMapper.getStudentInfoByMapParams(params);
                            if (null != studentInfoByMapParams) {
                                user = userMapper.getByPrimaryKey(studentInfoByMapParams.getUserId());
                            }
                            break;
                    }
                }
            }

            ResultDTO<AccountDto> result = wxFeignService.getAccountByOrg(orgId);
            if (result.isSuccess() && null != user) {
                AccountDto accountDto = result.getData();
                if (null != accountDto) {
                    youTuResult=youTuService.importUserFace(objects[5].toString(), user.getUserCode(), orgId, accountDto.getId(), user.getId(),false);
                    if (null!=youTuResult&&YouTuUtil.ERRORCODETYPE.equals(JSONObject.parseObject(youTuResult).get("errorcode"))) {
                        flag = true;
                    }
                }
            }

            if (null == user || !flag) {
                    errorMsgUserIdData.add(youTuResult);
            }
        }
        System.out.println(errorMsgUserIdData);
        importLog.setRemark(JSONObject.toJSONString(errorMsgUserIdData.toArray()));
        importLogMapper.insert(importLog);
        return errorMsgUserIdData;
    }

    @Override
    public void deletePerSonIdByOrgId(Long orgId) {
        try {
            log.info("********开始获取获取机构下所有个体********");
            String persons = youTuService.getPersons(orgId);

            if (JSONObject.parseObject(persons).get("errorcode").equals(YouTuUtil.ERRORCODETYPE)) {
                //获取所有个体
                JSONArray jsonArray = JSONObject.parseArray(JSONObject.parseObject(persons).get("person_list").toString());
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        String personId = JSONObject.parseObject(jsonArray.get(i).toString()).get("person_id").toString();

                        //通过用户个体查询用户ID
                        log.info("********开始获取个体对应的userId********");
                        YoutuPerson youtuPerson = webankService.getYoutuPersonByParam(personId);
                        youTuService.deletePerson(orgId, youtuPerson.getUserId());
                    }
                }
            }
            log.info("********获取机构下所有个体完成********", persons);
        } catch (Exception e) {
            log.error("********获取所有个体********", e.getMessage());
        }
    }

    @Override
    public void saveConfig(UserFacePersonConfig userFacePersonConfig) {
        //判断个体是否已存在
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", userFacePersonConfig.getOrgId());
        params.put("userId", userFacePersonConfig.getUserId());
        params.put("personId", userFacePersonConfig.getPersonId());
        UserFacePersonConfig oriUserFaceConfig = userFacePersonConfigMapper.getByMapParams(params);
        if (oriUserFaceConfig != null) {
            //相似度大于0,才修改
            if (null!=userFacePersonConfig.getSimilar() && userFacePersonConfig.getSimilar()>0){
                userFacePersonConfigMapper.update(userFacePersonConfig);
            }else{
                //相似度为空,删除配置数据
                userFacePersonConfigMapper.deleteByPrimaryKey(oriUserFaceConfig.getId());
            }
        } else {
            //相似度大于0才保存
            if(null!=userFacePersonConfig.getSimilar() && userFacePersonConfig.getSimilar()>0) {
                userFacePersonConfigMapper.insert(userFacePersonConfig);
            }
        }
    }

}
